import React, { PureComponent } from 'react';
import { message, Form, Tree, Card, Row, Col } from 'antd';
import { connect } from 'dva';
import SyOrderTableComponent from '../../components/SyOrderTableComponent';
import moment from 'moment';

const TreeNode = Tree.TreeNode;
const FormItem = Form.Item;
@Form.create()
@connect(state => ({
  modelState: state.systemRole,
}))
export default class SystemRole extends SyOrderTableComponent {

  _initSortion = { sortField: 'id', sortOrder: 'desc', };
  _initPagination = { pageSize: 10, current: 1, };
  _initCriteriaQuery = {};
  _operator = [
    {
      needForm: true,
      buttonLabel: '分配权限',
      modalTitle: '分配权限',
      modalWidth: 1200,
      buttonDisabled: 'more',//none： 一条记录都未选中时禁用,more：多条记录选中时禁用
      onClickEvent: () => {
        const { editedEntity } = this.state;
        if (editedEntity.authes) {
          let keys = [];
          for (let auth of editedEntity.authes) {
            keys.push(auth.id + "");
          }
          this.setState({
            checkedKeys: keys,
            expandedKeys: keys,
          });
        }
      },
      handleEvent: () => {
        let authes = [];
        for (let a of this.state.checkedKeys) {
          authes.push({ id: a });
        }
        this.state.editedEntity.authes = authes;

        const { dispatch } = this.props;

        dispatch({
          type: this.state.baseModel + '/edit',
          payload: {
            ...this.state.editedEntity,
          },
          callback: (code, msg) => {
            if (code == 200) {
              message.success(msg);
              this.resetCurrentForm();
              dispatch({
                type: this.state.baseModel + '/fetch',
                payload: {
                  ...this._initPagination,
                  ...this._initSortion,
                  ...this._initCriteriaQuery,
                }
              });
            } else {
              message.error(msg);
            }
          },
        });
      },
      renderForm: () => {
        const { modelState: { authRouterTree, authOperatorTree } } = this.props;
        return (
          <div>
            <Row>
              <Col span={12}>
                <Card title="导航权限" bordered={false} >
                  <Tree
                    checkStrictly={true}
                    checkable
                    defaultExpandAll
                    onExpand={this.onExpand}
                    expandedKeys={this.state.expandedKeys}
                    autoExpandParent={this.state.autoExpandParent}
                    onCheck={this.onCheck}
                    checkedKeys={this.state.checkedKeys}
                    onSelect={this.onSelect}
                    selectedKeys={this.state.selectedKeys}
                  >
                    {this.renderTreeNodes(authRouterTree)}
                  </Tree>
                </Card>
              </Col>
              <Col span={12}>
                <Card title="操作权限" bordered={false} >
                  <Tree
                    checkStrictly={true}
                    checkable
                    defaultExpandAll
                    onExpand={this.onExpand}
                    expandedKeys={this.state.expandedKeys}
                    autoExpandParent={this.state.autoExpandParent}
                    onCheck={this.onCheck}
                    checkedKeys={this.state.checkedKeys}
                    onSelect={this.onSelect}
                    selectedKeys={this.state.selectedKeys}
                  >
                    {this.renderTreeNodes(authOperatorTree)}
                  </Tree>
                </Card>
              </Col>
            </Row>
          </div>
        );
      },
    },
  ];

  onExpand = (expandedKeys) => {
    // if not set autoExpandParent to false, if children expanded, parent can not collapse.
    // or, you can remove all expanded children keys.
    this.setState({
      expandedKeys,
      autoExpandParent: false,
    });
  }

  onCheck = (checkedKeys) => {
    this.setState({ checkedKeys: checkedKeys.checked });
  }

  onSelect = (selectedKeys, info) => {
    this.setState({ selectedKeys });
  }

  renderTreeNodes = (data) => {
    return data.map((item) => {
      if (item.children) {
        return (
          <TreeNode title={item.title} key={item.key} dataRef={item}>
            {this.renderTreeNodes(item.children)}
          </TreeNode>
        );
      }
      return <TreeNode {...item} />;
    });
  }

  initSelection() {
    const { dispatch } = this.props;
    dispatch({
      type: 'systemRole/fetchSelectItems',
      payload: { service: '/user', apiUrl: '/system/organization', selectName: 'systemOrganizationSelectItems', current: 1, pageSize: 10000 }
    });
  }

  initAuthTree() {
    const { dispatch } = this.props;
    dispatch({
      type: 'systemRole/fetchAuthTree',
      payload: { service: '/user', apiUrl: '/system/auth', superAuthIsNull: true, authType: 'NAV', current: 1, pageSize: 10000 }
    });

    dispatch({
      type: 'systemRole/fetchAuthTree',
      payload: { service: '/user', apiUrl: '/system/auth', superAuthIsNull: true, authType: 'OPR', current: 1, pageSize: 10000 }
    });
  }

  componentWillMount() {
    this.initSelection();
    this.initAuthTree();
    this.setState({
      expandedKeys: [],
      autoExpandParent: true,
      checkedKeys: [],
      selectedKeys: [],
      needTableColumnsOperator: true,
      tableBorder: true,
      baseModel: 'systemRole',
      operator: this.operator,
      needAdd: true,
      needEdit: true,
      needDelete: true,
      needSearch: true,
      needTableCheckbox: true,
      tableScroll: { y: 800 },
      tableColumns: [
        {
          title: '角色名称',
          dataIndex: 'roleName',
          width: 240,
        },
        {
          title: '所属部门',
          dataIndex: 'organization.organizationName',
          width: 240,
        },
        {
          title: '备注',
          dataIndex: 'remark',
          width: 280,
          type: 'longString'
        },
        {
          title: '创建人',
          dataIndex: 'createUser.name',
          width: 160,
        },
        {
          title: '创建时间',
          dataIndex: 'createTime',
          // width: 200,
        },
      ],
      searchFormItem: [
        {
          name: 'roleName',
          label: '角色名称',
          placeholder: '角色名称',
          type: 'string',
          selectOption: [{ name: '', value: '' }],
        },
        {
          name: 'organizationId',
          label: '所属部门',
          placeholder: '所属部门',
          type: 'select',
          selectOption: { itemName: 'systemOrganizationSelectItems', name: 'organizationName', value: 'id', },
        },
      ],
      simpleAddFormItem: [
        {
          name: 'roleName',
          label: '角色名称',
          placeholder: '角色名称',
          type: 'string',
          rules: [{
            required: true, message: '请输入角色名称',
          }],
        },
        {
          name: 'organizationId',
          label: '所属部门',
          placeholder: '所属部门',
          type: 'select',
          selectOption: { itemName: 'systemOrganizationSelectItems', name: 'organizationName', value: 'id', },
          rules: [{
            required: true, message: '请选择所属部门',
          }],
        },
        {
          name: 'remark',
          label: '备注',
          placeholder: '备注',
          type: 'longString',
          selectOption: [{ name: '', value: '' }],
        },
      ],
      simpleEditFormItem: [
        {
          name: 'roleName',
          label: '角色名称',
          placeholder: '角色名称',
          type: 'string',
          selectOption: [{ name: '', value: '' }],
          rules: [{
            required: true, message: '请输入角色名称',
          }],
        },
        {
          name: 'organizationId',
          label: '所属部门',
          placeholder: '所属部门',
          type: 'select',
          selectOption: { itemName: 'systemOrganizationSelectItems', name: 'organizationName', value: 'id', },
          rules: [{
            required: true, message: '请选择所属部门',
          }],
        },
        {
          name: 'remark',
          label: '备注',
          placeholder: '备注',
          type: 'longString',
          selectOption: [{ name: '', value: '' }],
        },
      ],
    });
  }


}
